import sys
import csv
import json
from PyQt5 import QtCore, QtGui
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QApplication, QDialog, QMessageBox, QPushButton, QInputDialog

from view.Ui_plate_config import Ui_PlateConfig


# 从CSV文件中读取数据存储为list
# csv_file = csv.reader(open("../stockData.csv", 'r', encoding="utf-8"))
def getDataByCSV(filePath):
    csv_file = csv.reader(open(filePath, 'r', encoding="utf-8"))  # 以只读方式打开csv文件
    csv_list = []  # 定义存储整个csv文件的列表
    for line in csv_file:  # 按行对csv文件进行循环
        csv_list.append(line)  # 按行将csv文件读取到列表中
    return csv_list


# 从JSON文件中读取数据
def getDataByJSON(filePath='../data/plate.json'):
    with open(filePath, 'r', encoding='utf-8') as f:
        content = f.read()
        data = json.loads(content)
    return data


# 写入数据到JSON文件中
def writeData2JSON(filePath, json_list):
    with open(filePath, 'w', encoding='utf-8') as f:
        json.dump(json_list, f, ensure_ascii=False, indent=4)


class PlateConfig(QDialog, Ui_PlateConfig):
    def __init__(self):
        super(PlateConfig, self).__init__()
        self.plate0 = []  # 全部
        self.plate1 = []  # 主板
        self.plate2 = []  # 中小板
        self.plate3 = []  # 创业版
        self.plate4 = []  # 科创版
        self.myPlate = []  # 自选股
        self.setupUi(self)

        self.tabWidget.tabBar().hide()  # 隐藏标签
        # 连接下拉框改变的时间
        self.stockType.currentIndexChanged.connect(self.leftSelectionChange)
        self.plateType.currentIndexChanged.connect(self.on_plate_changed)

        self.newPlateBtn.clicked.connect(self.create_plate)  # 绑定新建板块按钮
        self.pushButton_2.clicked.connect(self.delete_plate)  # 绑定删除板块按钮
        self.load_plates()  # 加载板块数据

        self.initLeftList()  # 初始化左边的股票列表的数据
        # self.initRightList()  # 初始化右边的列表的数据

    # 初始化左左边的股票列表的数据
    def initLeftList(self):
        csvFilePath = "data/stockData.csv"
        csv_list = getDataByCSV(csvFilePath)

        rowCount = len(csv_list)  # 得到csv文件的行数
        # colCount = len(csv_list[0])  # 得到csv文件的列数
        for row in range(1, rowCount):
            # 划分板块数据
            stockType = csv_list[row][11]
            itemStr = "%s(%s)-%s" % (csv_list[row][1], csv_list[row][12], csv_list[row][2])
            self.plate0.append(itemStr)
            if stockType == "主板":
                self.plate1.append(itemStr)
            elif stockType == "中小板":
                self.plate2.append(itemStr)
            elif stockType == "创业板":
                self.plate3.append(itemStr)
            elif stockType == "科创板":
                self.plate4.append(itemStr)
            # 下拉框格式化显示,例: 000001(PAYH)-平安银行
            self.stockList.addItem(itemStr)

    # 初始化右边的列表的数据
    def initRightList(self):
        jsonFilePath = 'data/plate.json'
        json_list = getDataByJSON(jsonFilePath)
        for item in json_list:
            self.plateType.addItem(item['name'])
            if item['name'] == '自选股':  # 右边列表默认展示自选股板块
                for itemStr in item['stocks']:
                    self.addedList.addItem(itemStr)
                    self.myPlate.append(itemStr)  # 初始化自选股列表

    def leftSelectionChange(self, i):  # 切换左边下拉框选项时,切换列表的显示
        self.stockList.clear()  # 清空列表
        plate = []
        if i == 0:  # self.stockType.currentText() == "全部"
            plate = self.plate0  # 全部
        if i == 1:
            plate = self.plate1  # 主板
        if i == 2:
            plate = self.plate2  # 中小板
        if i == 3:
            plate = self.plate3  # 创业板
        if i == 4:
            plate = self.plate4  # 科创板
        for item in plate:
            self.stockList.addItem(item)

    def rightSelectionChange(self, i):  # 切换右边下拉框选项时,切换列表的显示
        pass

    def on_plate_changed(self):
        """板块切换时加载并显示该板块下的股票信息"""
        current_plate = self.plateType.currentText()  # 获取当前选中的板块
        if not current_plate:
            return

        # 查找选中的板块
        for plate in self.plates:
            if plate["name"] == current_plate:
                # 清空当前列表
                self.addedList.clear()
                # 加载该板块下的股票信息
                for stock_code in plate["stocks"]:
                    self.addedList.addItem(stock_code)
                break

    # 利用designer的信号与槽连接,不知为何,此处@pyqtSlot失效了...
    # 实现listWidget的实时搜索事件
    def on_search(self, str):
        items = self.stockList.findItems(str, QtCore.Qt.MatchContains)
        if len(items) > 0:
            items[0].setSelected(True)  # 选中
            index = self.stockList.selectedIndexes()[0]  # 获取索引
            self.stockList.verticalScrollBar().setSliderPosition(index.row())  # 设置滚动条

    # 将左边选中的股票,加入右边的自定义列表
    def on_add(self):
        if self.stockList.selectedIndexes():
            index = self.stockList.selectedIndexes()[0]  # 获取索引
            itemStr = self.stockList.item(index.row()).text()
            # 右边已经存在则不添加
            if self.addedList.findItems(itemStr, QtCore.Qt.MatchExactly):
                pass
            else:
                self.addedList.addItem(itemStr)  # 加入自定义列表
            # 添加完设置下一个元素为选中状态,若选中最后一个,不做操作
            if index.row() < self.stockList.count() - 1:
                self.stockList.item(index.row() + 1).setSelected(True)

    # 将右边选中的股票,从中移出
    def on_del(self):
        if self.addedList.selectedIndexes():
            index = self.addedList.selectedIndexes()[0]  # 获取索引
            self.addedList.takeItem(index.row())

    @pyqtSlot()
    def on_okBtn_clicked(self):
        jsonFilePath = 'data/plate.json'
        d = {'name': '自选股', 'stocks': []}
        rowCount = self.addedList.count()
        for i in range(rowCount):
            d['stocks'].append(self.addedList.item(i).text())
        json_list = [d] # 目前只有自选股板块,后续可能会增加自定义板块功能
        writeData2JSON(jsonFilePath, json_list)
        self.close()

    @pyqtSlot()
    def on_cancelBtn_clicked(self):
        self.close()


    def load_plates(self):
        """加载板块数据到下拉框"""
        try:
            with open("data/plate.json", "r", encoding="utf-8") as f:
                self.plates = json.load(f)
        except FileNotFoundError:
            self.plates = []

        self.plateType.clear()
        for plate in self.plates:
            self.plateType.addItem(plate["name"])

    def create_plate(self):
        """创建板块"""
        plate_name, ok = QInputDialog.getText(self, "新建板块", "请输入板块名称:")
        if ok and plate_name:
            # 检查板块是否已存在
            for plate in self.plates:
                if plate["name"] == plate_name:
                    QMessageBox.warning(self, "警告", "板块已存在！")
                    return

            # 添加新板块
            self.plates.append({"name": plate_name, "stocks": []})
            with open("data/plate.json", "w", encoding="utf-8") as f:
                json.dump(self.plates, f, ensure_ascii=False, indent=4)

            # 更新下拉框
            self.plateType.addItem(plate_name)

    def delete_plate(self):
        """删除板块"""
        if not self.plates:
            QMessageBox.warning(self, "警告", "没有可删除的板块！")
            return

        # 获取当前选中的板块
        current_plate = self.plateType.currentText()
        if not current_plate:
            QMessageBox.warning(self, "警告", "请先选择一个板块！")
            return

        # 确认删除
        reply = QMessageBox.question(self, "确认", f"确定要删除板块 '{current_plate}' 吗？",
                                     QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        if reply == QMessageBox.Yes:
            # 移除板块
            self.plates = [plate for plate in self.plates if plate["name"] != current_plate]
            with open("data/plate.json", "w", encoding="utf-8") as f:
                json.dump(self.plates, f, ensure_ascii=False, indent=4)

            # 更新下拉框
            self.plateType.removeItem(self.plateType.currentIndex())

    # # 处理关闭时的提示
    # def closeEvent(self, event):
    #     reply = QMessageBox.question(self, '退出', "确定要退出吗?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
    #     if reply == QMessageBox.Yes:
    #         event.accept()
    #     else:
    #         event.ignore()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ui = PlateConfig()
    ui.show()
    sys.exit(app.exec_())
